package main

import (

	"fmt"
	"time" 
	"gomore_client/protocol"
	"net"
	"os"
	"strconv"
	"github.com/google/flatbuffers/go"
	"bufio"
)



func createReqFlatbufferData( num int64) [][]byte {

	var reqs_bytes = [][]byte{}
	for i := 0; i < int(num); i++ {
		builder := flatbuffers.NewBuilder(0)
		cmd := builder.CreateByteString([]byte("socket.user_login"))
		req_data := builder.CreateByteString([]byte(string(time.Now().Unix())))
		sid := builder.CreateByteString([]byte(string(time.Now().Unix())))
		protocol.DataStart(builder)
		protocol.DataAdd_type(builder, int16(protocol.TypeReq))
		protocol.DataAddCmd(builder, cmd)
		protocol.DataAddSid(builder, sid  )
		protocol.DataAddData(builder, req_data)
		protocol.DataAddReqId(builder, int32(time.Now().Unix()))
		protocol.DataAddToken(builder, req_data)
		orc := protocol.DataEnd(builder)
		builder.Finish(orc)
		buf := builder.FinishedBytes()
		reqs_bytes = append(reqs_bytes, buf)
	}
	return reqs_bytes

}



func asyncReqFlatc(datas [][]byte) []*SocketResponse {

	//ch := make( chan *SocketResponse )
	responses := []*SocketResponse{}

	for _, data := range datas {
		go func(data []byte) {
			//fmt.Printf("Req %s \n", data)
			times, _ := strconv.ParseInt(os.Args[3], 10, 32)
			if len(os.Args) < 2 {
				fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
				os.Exit(1)
			}
			service := os.Args[1]
			tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
			checkError(err)
			conn, err := net.DialTCP("tcp", nil, tcpAddr)
			defer conn.Close()
			checkError(err)
			reqWithBufferio(conn, data, int(times))

		}(data)
	}

	return responses
}

func reqWithBufferio(conn *net.TCPConn, data []byte, times int) {

	conn.Write(append(data, '\n'))
	var i int
	i = 0
	sid := ""
	reader := bufio.NewReader(conn)

	for {
		buf, err := reader.ReadString('\n')
		//fmt.Println("handleConn ReadString: ", string(buf), "||")
		if err != nil {
			conn.Close()
			break
		}
		msg := protocol.GetRootAsData([]byte(buf), 0)
		cmd := string(msg.Cmd())

		if cmd == "socket.user_login" {
			sid = string(msg.Data())
			//fmt.Printf(" sid: %s\n", sid)
			//time.Sleep(10 * time.Millisecond )
			conn.Write(append(data, '\n'))
			//fmt.Printf(" i: %d\n", i)
			//fmt.Printf(" times: %d\n", times)
			i++
			if i > times {
				conn.Close()
				fmt.Println(" i : ", i, sid)
				fmt.Println(" conn close! ", i)
				break
			}
		}

	}
	conn.Close()

}